<script setup lang="ts">
import { request } from '@/api'
import { flattenAreaData } from '@/utils/area'
import b64toBlob from 'b64-to-blob'

import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { computed, onMounted, ref } from 'vue'

const columns = ref<any[]>([])

interface IPickerParams {
  selectedValues: string[] // 选中生日字符串数组
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}
// 相机选择器 打开相机
const isShowCamera = ref(false)
const onShowCamera = async (item: ActionSheetAction, index: number) => {
  if (index === 0) {
    // 打开相机
    const b64Str = await mk.pickerCamera()
    onUpdateAvatar(b64Str)
  } else {
    // 打开相册
    // 1.下包
    // 2.拿到base64
    const b64Str = await mk.pickerPhoto()
    onUpdateAvatar(b64Str)
  }
}

const onUpdateAvatar = async (str: string) => {
  // 3.转换为2进制blob
  isShowCamera.value = false
  const file = b64toBlob(str, 'image/jpeg')

  // 4.fd组装数据、
  const fd = new FormData()
  fd.append('file', file, Date.now() + '.jpeg')
  showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
  // 5.调用上传接口
  const res = await request.post('member/profile/avatar', fd)
  profile.value.avatar = res.data.result.avatar

  showToast('上传成功')
}
// 日期选择器 选择日期
const isShowBirth = ref(false)
const onSelectBirth = ({ selectedValues }: IPickerParams) => {
  //console.log('selectedValues---->', selectedValues)
  profile.value.birthday = selectedValues.join('-')

  isShowBirth.value = false
}

// 选择地区
const isShowArea = ref(false)
const str = mk.getAreaColumns()
columns.value = JSON.parse(str)
const areaData = flattenAreaData(JSON.parse(str))

const onSelectArea = (data: IPickerParams) => {
  const pName = areaData[data.selectedValues[0]]
  const cName = areaData[data.selectedValues[1]]
  const aName = areaData[data.selectedValues[2]]

  // A. 收集省市区的code
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]

  console.log('pName  ----->  ', pName)
  console.log('cName  ----->  ', cName)
  console.log('aName  ----->  ', aName)
  profile.value.fullLocation = `${pName} ${cName} ${aName}`
  isShowArea.value = false
}

//
// 4. 选择职业
const columnPro = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}

const birthList = computed(() => {
  return profile.value.birthday.split('-')
})

// a.查询数据和存数据
const profile = ref({} as HDMUser) // 用户数据
onMounted(() => {
  profile.value = mk.queryUser() // 通过mk，调用鸿蒙的查询用户数据方法
})

// B. 绑定点击事件
const onSubmit = async () => {
  // C. 调用保存的接口
  const res = await request.put('/member/profile', profile.value)
  console.log('res  ----->  ', res)
  // D. 更新数据到鸿蒙App
  // E. 修复用户数据更新到首选项中
  mk.updateUser(res.data.result)
  showToast('修改成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
      </van-image>
      <div class="avatar-btn" @click="isShowCamera = true">
        <span>修改头像</span>
      </div>
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>

      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        v-model="profile.birthday"
        @click="isShowBirth = true"
      ></van-field>

      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        v-model="profile.fullLocation"
        @click="isShowArea = true"
      ></van-field>

      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        v-model="profile.profession"
        @click="showProfessionPopup = true"
      ></van-field>
    </van-cell-group>

    <div class="submit" @click="onSubmit">
      <van-button round block type="primary"> 保存资料 </van-button>
    </div>

    <van-action-sheet
      @select="onShowCamera"
      cancel-text="取消"
      v-model:show="isShowCamera"
      :actions="[{ name: '相机' }, { name: '相册' }]"
    ></van-action-sheet>
    <!-- 生日 -->
    <VanPopup v-model:show="isShowBirth" position="bottom">
      <VanDatePicker
        title="选择生日"
        v-model="birthList"
        @cancel="isShowBirth = false"
        @confirm="onSelectBirth"
        :min-date="new Date('1900-01-01')"
        :max-date="new Date()"
      ></VanDatePicker>
    </VanPopup>
    <!-- 地区 -->
    <VanPopup v-model:show="isShowArea" position="bottom">
      <!-- 传值： -->
      <VanPicker
        title="选择地区"
        :columns="columns"
        :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"
        @confirm="onSelectArea"
      ></VanPicker>
    </VanPopup>
    <!-- 职业 -->
    <van-popup v-model:show="showProfessionPopup" round position="bottom">
      <van-picker
        :columns="columnPro"
        @confirm="onChangeProfession"
        @cancel="showProfessionPopup = false"
      />
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px #ccc;
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
